import { wptBridgeNativeCallBack, wptBridgeNativeCallJs, wptBridgeJsCallBack } from './core';
import ForNativeJsAggregete from './class/ForNativeJsAggregete';
import importOldVersionJSBridge from './oldVersion';
import { isWPTApp, logError } from './util';

const gFunctions = {
    a: (data, eventId) => {
        console.log('a Function called');
        if (eventId) {
            wptBridgeJsCallBack({
                eventId,
                params: {
                    b: 2,
                },
            });
        }
    },
};

/**
 *设置全局函数
 *
 * @param {*} functions
 */
function addGlobalFunction(functions) {
    Object.keys(functions).forEach(key => {
        if (typeof functions[key] === 'function') {
            ForNativeJsAggregete.add(key, functions[key]);
        } else {
            logError('设置ForNativeJsAggregete的值必须为函数');
        }
    });
}

function initWptBridge() {
    if (isWPTApp) {
        addGlobalFunction(gFunctions);
        window.wptBridgeNativeCallBack = wptBridgeNativeCallBack;
        window.wptBridgeNativeCallJs = wptBridgeNativeCallJs;
        // 引入版本376之前的 jsBridge 文件
        importOldVersionJSBridge();
    }
}

export { initWptBridge };
